import request, { localService } from './base/request'
import { AxiosPromise } from 'axios'
import { downLoadBlob, downLoadFile, getFileExt, getFileName, popMessage } from '../utils/normalUtils'

/** @description:基础服务*/
const URL_API = (import.meta as any).env.VITE_APP_BASE_API !== null
        ? (import.meta as any).env.VITE_APP_BASE_API?.toString()
        : ''

/** @description:权限验证服务*/
const USER_API = (import.meta as any).env.VITE_APP_USER_API !== null
    ? (import.meta as any).env.VITE_APP_USER_API?.toString()
    : ''

/**
 * 基本服务
 * @param url
 * @param method
 * @param params
 * @param options
 */
export function baseService(url:string, method = 'get', params:any = null, options:any = null, responseType:any = null, timeout:any = null):AxiosPromise {
    return executeService(URL_API, url, method, params, options, responseType, timeout)
}

/**
 * 权限验证服务
 * @param url
 * @param method
 * @param params
 * @param options
 */
export function authService(url:string, method = 'get', params:any = null, options:any = null, responseType:any = null, timeout:any = null):AxiosPromise {
    return executeService(USER_API, url, method, params, options, responseType, timeout)
}

/**
 * 通用服务
 * @param baseurl
 * @param url
 * @param method
 * @param params
 * @param options
 */
export function executeService(baseurl:string, url:string, method = 'get', params:any = null, options:any = null, responseType:any = null, timeout:any = null):AxiosPromise {
    method = method.toLocaleLowerCase()
    const sendData:any = {
        baseURL: baseurl,
        url,
        method: method === 'deletebody' ? 'delete' : method,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        xhrFields: {
            withCredentials: true
        },
        responseType,
        timeout: timeout || 50000
    }
    if (!params) { params = {} }
    if (method === 'post' || method === 'put' || method === 'deletebody') {
        sendData.data = params
    } else {
        params._r_d = `r_d_${Math.random() * 100}`
        sendData.params = params
    }
    if (options) { Object.assign(sendData, options) }
    return request(sendData)
}

export function localJsonFile(url:string, options:any = null) {
    const send = { url, method: 'get' }
    if (options)Object.assign(send, options)
    return localService(send)
}

/**
 * 加载本地文本
 * @param url
 * @param options
 */
export function localTextFile(url:string, options:any = null) {
    const send = {
        url,
        method: 'get',
        contentType: 'text/plain;charset=utf-8',
        dataType: 'text',
        xhrFields: {
            withCredentials: true
        }
    }
    if (options)Object.assign(send, options)
    return localService(send)
}

/**
 * 处理上传表单数据
 * @param params
 * @return FormData
 */
export function renderFormData(params:any):FormData {
    const formData = new FormData()
    for (const att in params) {
        const item = params[att]
        // 只按两层处理
        if (Array.isArray(item)) {
            item.forEach((file) => formDataAppend(formData, att, file))
        } else {
            formDataAppend(formData, att, item)
        }
    }
    return formData
}


/**
 * 添加表单数据
 * @param formData
 * @param att
 * @param item
 */
function formDataAppend(formData:FormData, att:any, item:any) {
    // 如果没有值 加空
    if (item === null || item === undefined) {
        formData.append(att, '')
        return
    }
    if (item instanceof File) {
        formData.append(att, item, item.name)
    } else if (typeof item !== 'object') {
        formData.append(att, item)
    }
    // formData.append(att,  jsonString(item), "");
}

/**
 *  上面的都不用了
 * @param method
 * @param params
 * @param proxyLoading
 * @param error
 */
export function sendServiceData(method:any, params:any = null, proxyLoading:any = null, error = true, errorNull = false):Promise<any> {
    setProxyLoading(proxyLoading, true)
    return new Promise((resolve, reject) => {
        method(params || {})
            .then((result: any) => {
                setProxyLoading(proxyLoading, false)
                resolve(result)
            }).catch((res: any) => {
            setProxyLoading(proxyLoading, false)
            if (!error) resolve(res)
            else if (errorNull)resolve(null)
        })
    })
}

/**
 *
 * @param proxyLoading
 * @param value
 */
function setProxyLoading(proxyLoading:any, value:boolean) {
    if (!proxyLoading) return
   if (typeof proxyLoading === 'function')proxyLoading(value)
   else proxyLoading.isLoading = value
}

/**
 * 基础服务地址
 * @param url
 */
export function getBaseServiceUrl(url:string) {
    return URL_API + url
}

/**
 * 用户服务地址
 * @param url
 */
export function getUserServiceUrl(url:string) {
    return USER_API + url
}

/**
 * 下载服务端小文件
 */
export async function downServiceFile(url:any, fileName = '', params:any = {}, options:any = null, method = 'get', blankFileMsg = '') {
    if (!options)options = {}
    options.responseType = 'blob'
    options.timeout = 30 * 60 * 1000
    const result:any = await baseService(url, method, params, options)
    let fileData = result.data
    if (!fileData) {
        if (blankFileMsg) {
            popMessage(blankFileMsg)
            return
        }
        fileData = new Blob()
    }
    if (!fileName) {
        if (result.fileName)fileName = result.fileName
        else getFileName(url)
    }
    downLoadBlob(fileData, fileName)
}

/**
 * 地址栏拼接删除多个ID写法兼容下 数据多了会有问题temp????
 * @param params
 */
export function getUrlDeleteId(params:any) {
    return (Array.isArray(params)) ? params.join(',') : params.id
}

export { URL_API }
